import 'package:capsule/models/config_file_type.dart';
import 'package:capsule/utils/file_utils.dart';
import 'package:capsule/utils/global_variables.dart';
import 'package:pinyin/pinyin.dart';

class FileInfo {
  String? _title;
  final String fullPath;
  String? _extension;
  String? _name;

  String? _category;

  final int? size;
  final int? idInDB;

  String? _sizeString;
  String? _fileTypeName;
  final int? lastAccessed;
  final int? lastModified;
  String? _shortPinyin;
  String? summary;
  String? shelf;
  FileInfo(this.fullPath,
      {this.size,
      this.idInDB,
      this.shelf,
      String? fileTypeName,
      this.lastAccessed,
      this.lastModified,
      this.summary,
      String? shortPinyin})
      : _fileTypeName = fileTypeName,
        _shortPinyin = shortPinyin {
    _parsePath();
  }

  void _parsePath() {
    String pathTemp = fullPath.replaceAll("\\", "/");
    List<String> parts = pathTemp.split("/");
    _name = parts[parts.length - 1];
    _category = parts.length > 1 ? null : parts[parts.length - 2];
    List<String> nameParts = _name!.split(".");
    _extension = nameParts.length >= 2 ? nameParts[nameParts.length - 1] : null;
    _title = _extension != null
        ? _name!.substring(0, _name!.length - _extension!.length - 1)
        : _name;
  }

  String get title => _title!;
  String get name => _name!;

  String? get ext => _extension;
  String? get category => _category;
  String? get fileTypeName {
    if (_fileTypeName == null) {
      if (appConfig.fileTypes != null) {
        for (final ConfigFileType fileType in appConfig.fileTypes!) {
          if (fileType.extensions != null) {
            if (fileType.extensions!.contains(".$_extension")) {
              _fileTypeName = fileType.name;
              break;
            }
          }
        }
      }
    }
    return _fileTypeName;
  }

  String? get sizeString {
    if (_sizeString != null) {
      return _sizeString;
    } else {
      if (size != null) {
        _sizeString = getFileSizeString(bytes: size!);
        return _sizeString;
      }
    }
    return null;
  }

  String? get shortPinyin {
    if (_shortPinyin == null) {
      String temp = name.length > 5 ? name.substring(0, 6) : name;
      _shortPinyin = PinyinHelper.getShortPinyin(temp);
    }
    return _shortPinyin;
  }

  FileInfo copyWith(
      {String? fullPath,
      int? size,
      int? idInDB,
      int? lastAccessed,
      int? lastModified,
      String? summary,
      String? shelf}) {
    return FileInfo(fullPath ?? this.fullPath,
        size: size ?? this.size,
        idInDB: idInDB ?? this.idInDB,
        lastAccessed: lastAccessed ?? this.lastAccessed,
        lastModified: lastModified ?? this.lastModified,
        summary: summary ?? this.summary,
        shelf: shelf ?? this.shelf);
  }
}
